import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../components/Layout/Layout'
import arr1 from './yuyue'
import arr2 from './yiyuanxinxi'
import Login from '../views/Login'
import Home from '../views/home/home'
import register from '../components/yuyue/register'
import store from '../store/index.js'
Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'sss',
    component: Layout,
    redirect: '/home',
    children: [{
            path: 'home',
            name: 'home',
            component: Home,
            meta: { title: '首页', title2: '张容宇' },


        },

        {
            path: 'register',
            name: 'register',
            component: register,
            meta: { title: '预约挂号', yuyue: 'yuyue', title2: '王雅倩' },

        }, ...arr1, ...arr2
    ]
}, {
    path: '/login',
    name: 'logine',
    component: Login,
    meta: { title: '登录' },
}, {
    path: '*',
    component: () =>
        import ('@/components/yuyue/404')
}]
Vue.use(VueRouter)


const router = new VueRouter({
    routes
})


let baimingdan = ['/login']

import { getToken } from '../utils/cookieUtils'

import { getUser } from '../api/login'

router.beforeEach((to, form, next) => {
    let token = getToken('token')

    if (token) {
        if (to.path == '/login') {
            next('/')

        } else {

            if (store.state.menu.length == 0) {

                getUser(token).then(res => {


                    let letidentity = res.data.power

                    store.commit('setUserMsg', res.data)



                    store.commit('setUserMsg', res.data)

                    if (letidentity == '用户') {
                        routes[0].children = routes[0].children.filter(item => {
                            return !item.meta.rlue
                        })
                        let userArr = routes[0].children

                        store.commit('setUserMenu', userArr)

                        router.addRoutes(routes)
                        next({...to, replace: true })

                    } else {
                        store.commit('setUserMenu', routes[0].children)
                        next()

                    }


                })

            } else {
                next()
            }

        }




    } else {

        let b = baimingdan.find(item => item == to.path)
        if (b) {
            next()
        } else {
            next('/login')
        }
    }

})

export default router